package com.laizhenghua.wxstub.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.laizhenghua.wxstub.constant.AppConstant;
import com.laizhenghua.wxstub.service.CacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @author: laizhenghua
 * @date: 2022/8/31 22:32
 */
@Service("cacheService")
public class CacheServiceImpl implements CacheService {
    private static final org.apache.logging.log4j.Logger log = org.apache.logging.log4j.LogManager.getLogger(CacheServiceImpl.class);
    @Autowired
    private RestTemplate restTemplate;

    @Override
    @Cacheable(value = "accessTokenCache", key = "#root.method.name")
    public String getAccessToken() {
        Map<String, Object> params = new HashMap<>();
        params.put("appId", AppConstant.WX_APP_ID);
        params.put("secret", AppConstant.WX_APP_SECRET);
        JSONObject response = restTemplate.getForObject(AppConstant.WX_BASE_URL + "token?grant_type=client_credential&appid={appId}&secret={secret}",
                JSONObject.class, params);
        log.info(JSON.toJSONString(response));
        if (response == null) {
            log.info("获取access_token失败！");
            return null;
        }
        String accessToken = response.getString("access_token");
        if (accessToken == null) {
            log.error(response.getString("errcode"));
            return null;
        }
        return accessToken;
    }
}
